<?php
/**
 * tpshop
 * ============================================================================
 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 采用TP5助手函数可实现单字母函数M D U等,也可db::name方式,可双向兼容
 * ============================================================================
 * 2015-11-21
 */
namespace app\mobile\controller;

use app\common\logic\CartLogic;
use app\common\logic\MessageLogic;
use app\common\logic\UsersLogic;
use app\common\logic\OrderLogic;
use app\common\logic\JssdkLogic;
use think\Page;
use think\Request;
use think\Verify;
use think\db;

class User extends MobileBase
{

    public $user_id = 0;
    public $user = array();

    /*
    * 初始化操作
    */
    public function _initialize()
    {
        parent::_initialize();
        if (session('?user')) {
            $user = session('user');
            $user = M('users')->where("user_id", $user['user_id'])->find();
            session('user', $user);  //覆盖session 中的 user
            $this->user = $user;
            $this->user_id = $user['user_id'];
            $this->assign('user', $user); //存储用户信息
        }
        $nologin = array(
            'login', 'pop_login', 'do_login','wx_login','gongzhonghao','carttongji',  'logout', 'verify', 'set_pwd', 'finished',
            'verifyHandle', 'reg', 'send_sms_reg_code', 'find_pwd', 'check_validate_code',
            'forget_pwd', 'check_captcha', 'extended', 'check_username', 'send_validate_code', 'express',
        );
        if (!$this->user_id && !in_array(ACTION_NAME, $nologin)) {
            header("location:" . U('Mobile/User/login'));
            exit;
        }

        $order_status_coment = array(
            'WAITPAY' => '待付款 ', //订单查询状态 待支付
            'WAITSEND' => '待发货', //订单查询状态 待发货
            'WAITRECEIVE' => '待收货', //订单查询状态 待收货
            'WAITCCOMMENT' => '待评价', //订单查询状态 待评价
        );
        $this->assign('order_status_coment', $order_status_coment);
    }

    /*
     * 用户中心首页
     */
    public function index()
    {
        $user_id =$this->user_id;
        $logic = new UsersLogic();
        $user = $logic->get_info($user_id); //当前登录用户信息
        $comment_count = M('comment')->where("user_id", $user_id)->count();   // 我的评论数

        $level_name = M('user_level')->where("level_id", $this->user['level'])->getField('level_name'); // 等级名称

        
        //获取用户信息的数量        
        $messageLogic = new MessageLogic();
        $user_message_count = $messageLogic->getUserMessageCount();
        $this->assign('user_message_count', $user_message_count);
        $this->assign('level_name', $level_name);
        $this->assign('comment_count', $comment_count);
        $this->assign('user',$user['result']);
        if(empty($_SESSION['user_address'])){
            $this->assign('user_address',0);
        }else{
            $this->assign('user_address',1);
        }
        
        //如果是微信浏览器并且没有用户地址
        if(strstr($_SERVER['HTTP_USER_AGENT'],'MicroMessenger')&&empty($_SESSION['user_address'])){
            $this->weixin_config = M('wx_user')->find(); //获取微信配置       
            // 微信Jssdk 操作类             
            $jssdk = new JssdkLogic($this->weixin_config['appid'], $this->weixin_config['appsecret']);
            $signPackage = $jssdk->GetSignPackage();          
            $this->assign('signPackage', $signPackage);
        }
        return $this->fetch();
    }

    /**
     * 退出个人中心
     */
    public function logout()
    {
        session_unset();
        session_destroy();
        setcookie('uname','',time()-3600,'/');
        setcookie('cn','',time()-3600,'/');
        setcookie('user_id','',time()-3600,'/');
        setcookie('PHPSESSID','',time()-3600,'/');
        //$this->success("退出成功",U('Mobile/Index/index'));
        //header("Location:" . U('Mobile/Index/index'));
        $this->redirect('mobile/Index/index');
        exit();
    }

    /**
     * 账户资金
     */
    public function account()
    {
        $user = session('user');
        //获取账户资金记录
        $logic = new UsersLogic();
        $data = $logic->get_account_log($this->user_id, I('get.type'));
        $account_log = $data['result'];

        $this->assign('user', $user);
        $this->assign('account_log', $account_log);
        $this->assign('page', $data['show']);

        if ($_GET['is_ajax']) {
            return $this->fetch('ajax_account_list');
            exit;
        }
        return $this->fetch();
    }

    /**
     * 账户库存
     */
    public function kucun()
    {
        $user = session('user');        
        //获取库存记录
        $type = I('type','all');
        $this->assign('type', $type);
        $goods_lists=M('goods')->select();
        foreach ($goods_lists as $key => $value) {
                $goods_list[$value['goods_id']]=$value;
            }
         //获取账户库存
        $user_kucun=M('users_kucun')->where(array('user_id'=>$user['user_id']))->find();
        $user_kucun=unserialize($user_kucun['kucun']);                      
        $this->assign('user_kucun', $user_kucun);
        $this->assign('goods_list', $goods_list);
        if($type=='all'){
            // $count = M('users_kucun_log')->where(array('user_id'=>$user['user_id']))->count();
            // $Page = new Page($count, 6);
            // $users_kucun_log = M('users_kucun_log')->where(array('user_id'=>$user['user_id']))->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
            // $showpage = $Page->show();           
            // $page = I('page',2);
            if ($_GET['is_ajax']){
                return '';
            }          
        }else{
            $count = M('users_kucun_log')->where(array('user_id'=>$user['user_id'],'status'=>$type))->count();
            if($type==1){                
                $order_infos=M('order')->where(array('user_id'=>$user['user_id'],'sendkc'=>2))->select();
                $order_info=null;
                if($order_infos){
                    foreach ($order_infos as $key => $value) {
                        if($value['order_status']==6){
                            $order_info[$value['order_id']]='已入库';
                        }else{
                            $order_info[$value['order_id']]='待入库';
                        }                        
                    }                    
                }
                $this->assign('order_info', $order_info);
            }elseif($type==2){
                $tihuo_infos=M('users_tihuo')->where(array('user_id'=>$user['user_id']))->select();                
                $tihuo_info=null;
                if($tihuo_infos){
                    foreach ($tihuo_infos as $key => $value) {
                        if($value['order_status']==1&&$value['shipping_status']==0){
                            $tihuo_info[$value['id']]='待审核';
                        }
                        if($value['order_status']==2&&$value['shipping_status']==0){
                            $tihuo_info[$value['id']]='待发货';
                        }
                        if($value['order_status']==3&&$value['shipping_status']==1){
                            $tihuo_info[$value['id']]='待收货';
                        }
                        if($value['order_status']==4&&$value['shipping_status']==1){
                            $tihuo_info[$value['id']]='已完成';
                        }
                    }                    
                }
                $this->assign('tihuo_info', $tihuo_info);
            }
            $Page = new Page($count, 6);
            $users_kucun_log = M('users_kucun_log')->where(array('user_id'=>$user['user_id'],'status'=>$type))->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
            $showpage = $Page->show();
            $this->assign('users_kucun_log', $users_kucun_log);
            $this->assign('page', $showpage);
            $this->assign('listRows', $Page->listRows);
            if($_GET['is_ajax']){
                return $this->fetch('ajax_kucun');
            }
        }        
        return $this->fetch();
    }

    public function account_list()
    {
    	$type = I('type','all');
    	$usersLogic = new UsersLogic;
    	$result = $usersLogic->account($this->user_id, $type);
    
    	$this->assign('type', $type);
    	$this->assign('account_log', $result['account_log']);
    	if ($_GET['is_ajax']) {
    		return $this->fetch('ajax_account_list');
    	}
    	return $this->fetch();
    }

    public function account_detail(){
        $log_id = I('log_id/d',0);
        $detail = Db::name('account_log')->where(['log_id'=>$log_id])->find();
        $this->assign('detail',$detail);
        return $this->fetch();
    }
    
    /**
     * 优惠券
     */
    public function coupon()
    {
        $logic = new UsersLogic();
        $data = $logic->get_coupon($this->user_id, input('type'));
        $coupon_list = $data['result'];
        $this->assign('coupon_list', $coupon_list);
        $this->assign('page', $data['show']);
        if (input('is_ajax')) {
            return $this->fetch('ajax_coupon_list');
            exit;
        }
        return $this->fetch();
    }

    /**
     * 确定订单的使用优惠券
     * @author lxl
     * @time 2017
     */
    public function checkcoupon()
    {
        $type = input('type');
        $now = time();
        $cartLogic = new CartLogic();
        // 找出这个用户的优惠券 没过期的  并且 订单金额达到 condition 优惠券指定标准的
        $cartLogic->setUserId($this->user_id);
        $cartList = $cartLogic->getCartList(1);//获取购物车商品
        $cartTotalPrice = array_sum(array_map(function($val){return $val['total_fee'];}, $cartList));//商品优惠总价
        $where = '';
        if(empty($type)){
            $where = " c2.uid = {$this->user_id} and {$now} < c1.use_end_time and {$now} > c1.use_start_time and c1.condition <= {$cartTotalPrice} ";
        }
        if($type == 1){
           $where = " c2.uid = {$this->user_id} and c1.use_end_time < {$now} or c1.use_start_time > {$now} or {$cartTotalPrice}  < c1.condition ";
        }
        $coupon_list = DB::name('coupon')
            ->alias('c1')
            ->field('c1.name,c1.money,c1.condition,c1.use_end_time, c2.*')
            ->join('coupon_list c2','c2.cid = c1.id and c1.type in(0,1,2,3) and order_id = 0','LEFT')
            ->where($where)
            ->select();
        $this->assign('coupon_list', $coupon_list); // 优惠券列表
        return $this->fetch();
    }

    /**
     *  登录
     */
    public function login()
    {
        //不进登录页面直接微信登录
        if(strstr($_SERVER['HTTP_USER_AGENT'],'MicroMessenger')){
            header("Location: " . U('mobile/user/wx_login'));
            exit;
        }
        if ($this->user_id > 0) {
//
//            header("Location: " . U('Mobile/User/index'));
        }
        $referurl = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : U("Mobile/User/index");
        $this->assign('referurl', $referurl);        
        return $this->fetch();
    }

    /**
     * 登录
     */
    public function do_login()
    {
        $username = trim(I('post.username'));
        $password = trim(I('post.password'));
        //验证码验证
        // if (isset($_POST['verify_code'])) {
        //     $verify_code = I('post.verify_code');
        //     $verify = new Verify();
        //     if (!$verify->check($verify_code, 'user_login')) {
        //         $res = array('status' => 0, 'msg' => '验证码错误');
        //         exit(json_encode($res));
        //     }
        // }
        $logic = new UsersLogic();
        $res = $logic->login($username, $password);
        if ($res['status'] == 1) {
            $res['url'] = urldecode(I('post.referurl'));
            session('user', $res['result']);
            setcookie('user_id', $res['result']['user_id'], null, '/');
            setcookie('is_distribut', $res['result']['is_distribut'], null, '/');
            $nickname = empty($res['result']['nickname']) ? $username : $res['result']['nickname'];
            setcookie('uname', urlencode($nickname), null, '/');
            setcookie('cn', 0, time() - 3600, '/');
            $cartLogic = new CartLogic();
            $cartLogic->setUserId($res['result']['user_id']);
            $cartLogic->doUserLoginHandle();// 用户登录后 需要对购物车 一些操作
//            $cartLogic->login_cart_handle($this->session_id, $res['result']['user_id']);  //用户登录后 需要对购物车 一些操作
        }
        exit(json_encode($res));
    }

    /**
     *  注册
     */
    public function reg()
    {

        if($this->user_id > 0) {
            $this->redirect(U('Mobile/User/index'));
//            $this->ajaxReturn(['status'=>1,'msg'=>'您已注册']);
        }
        $reg_sms_enable = tpCache('sms.regis_sms_enable');
        $reg_smtp_enable = tpCache('sms.regis_smtp_enable');

        if (IS_POST) {
            $logic = new UsersLogic();
            //验证码检验
            //$this->verifyHandle('user_reg');
            $username = I('post.username', '');
            $password = I('post.password', '');
            $password2 = I('post.password2', '');
            //是否开启注册验证码机制
            $code = I('post.mobile_code', '');
            $scene = I('post.scene', 1);

            $session_id = session_id();

            //是否开启注册验证码机制
            if(check_mobile($username)){
                if($reg_sms_enable){
                    //手机功能没关闭
                    $check_code = $logic->check_validate_code($code, $username, 'phone', $session_id, $scene);
                    if($check_code['status'] != 1){
                        $this->ajaxReturn($check_code);
                    }
                }
            }
            //是否开启注册邮箱验证码机制
            if(check_email($username)){
                if($reg_smtp_enable){
                    //邮件功能未关闭
                    $check_code = $logic->check_validate_code($code, $username);
                    if($check_code['status'] != 1){
                        $this->ajaxReturn($check_code);
                    }
                }
            }
            $invite = I('invite');
            if(!empty($invite)){
            	$invite = get_user_info($invite,2);//根据手机号查找邀请人
            }
            $data = $logic->reg($username, $password, $password2,0,$invite);
            if ($data['status'] != 1)
                $this->ajaxReturn($data['msg']);
            $first_leader=$_SESSION['fuid'];
            if($first_leader){
                M('users')->where(array('user_id'=>$data['result']['user_id']))->save(array('first_leader'=>$first_leader));
            }
            session('user', $data['result']);
            setcookie('user_id', $data['result']['user_id'], null, '/');
            setcookie('is_distribut', $data['result']['is_distribut'], null, '/');
            $cartLogic = new CartLogic();
            $cartLogic->setUserId($data['result']['user_id']);
            $cartLogic->doUserLoginHandle();// 用户登录后 需要对购物车 一些操作
            $this->ajaxReturn($data);
            exit;
        }
        if(I('get.fuid')){
            $_SESSION['fuid']=I('get.fuid');
        }
        //不进登录页面直接微信登录
        if(strstr($_SERVER['HTTP_USER_AGENT'],'MicroMessenger')){
            header("Location: " . U('mobile/user/wx_login'));
            exit;
        }
        $this->assign('regis_sms_enable',$reg_sms_enable); // 注册启用短信：
        $this->assign('regis_smtp_enable',$reg_smtp_enable); // 注册启用邮箱：
        $sms_time_out = tpCache('sms.sms_time_out')>0 ? tpCache('sms.sms_time_out') : 120;
        $this->assign('sms_time_out', $sms_time_out); // 手机短信超时时间
        return $this->fetch();
    }

    /*
     * 订单列表
     */
    public function order_list()
    {
        $where = ' user_id=' . $this->user_id;
        //条件搜索
       if(I('get.type')){
            $where .= C(strtoupper(I('get.type')));
       }   
        $count = M('order')->where($where)->count();
        $Page = new Page($count, 10);
        $show = $Page->show();
        $order_str = "order_id DESC";
        $order_list = M('order')->order($order_str)->where($where)->limit($Page->firstRow . ',' . $Page->listRows)->select();

        //获取订单商品
        $model = new UsersLogic();
        foreach ($order_list as $k => $v) {
            $order_list[$k] = set_btn_order_status($v);  // 添加属性  包括按钮显示属性 和 订单状态显示属性
            //$order_list[$k]['total_fee'] = $v['goods_amount'] + $v['shipping_fee'] - $v['integral_money'] -$v['bonus'] - $v['discount']; //订单总额
            $data = $model->get_order_goods($v['order_id']);
            $order_list[$k]['goods_list'] = $data['result'];
             //查看当前用户线下支付是否提交了凭证
            $order_list[$k]['pay_offline_status'] = M('offline_evidence')->where('order_id='.$v['order_id'])->count();
        }
//        print_r($order_list);die;
        //统计订单商品数量
        foreach ($order_list as $key => $value) {
            $count_goods_num = '';
            foreach ($value['goods_list'] as $kk => $vv) {
                $count_goods_num += $vv['goods_num'];
            }
            $order_list[$key]['count_goods_num'] = $count_goods_num;
        }
       
        
        $this->assign('order_status', C('ORDER_STATUS'));
        $this->assign('shipping_status', C('SHIPPING_STATUS'));
        $this->assign('pay_status', C('PAY_STATUS'));
        $this->assign('page', $show);
        $this->assign('lists', $order_list);
        $this->assign('active', 'order_list');
        $this->assign('active_status', I('get.type'));
        if ($_GET['is_ajax']) {
            return $this->fetch('ajax_order_list');
            exit;
        }
        return $this->fetch();
    }


    /*
     * 订单详情
     */
    public function order_detail()
    {
        $id = I('get.id/d');
        $map['order_id'] = $id;
        $map['user_id'] = $this->user_id;
        $order_info = M('order')->where($map)->find();
        $order_info = set_btn_order_status($order_info);  // 添加属性  包括按钮显示属性 和 订单状态显示属性
        if (!$order_info) {
            $this->error('没有获取到订单信息');
            exit;
        }
        //获取订单商品
        $model = new UsersLogic();
        $data = $model->get_order_goods($order_info['order_id']);
        $order_info['goods_list'] = $data['result'];
        //$order_info['total_fee'] = $order_info['goods_price'] + $order_info['shipping_price'] - $order_info['integral_money'] -$order_info['coupon_price'] - $order_info['discount'];

        $region_list = get_region_list();
        $invoice_no = M('DeliveryDoc')->where("order_id", $id)->getField('invoice_no', true);
        $order_info[invoice_no] = implode(' , ', $invoice_no);
        //获取订单操作记录
        $order_action = M('order_action')->where(array('order_id' => $id))->select();
        $this->assign('order_status', C('ORDER_STATUS'));
        $this->assign('shipping_status', C('SHIPPING_STATUS'));
        $this->assign('pay_status', C('PAY_STATUS'));
        $this->assign('region_list', $region_list);
        $this->assign('order_info', $order_info);
        $this->assign('order_action', $order_action);

        if (I('waitreceive')) {  //待收货详情
            return $this->fetch('wait_receive_detail');
        }
        return $this->fetch();
    }

    public function express()
    {
        $order_id = I('get.order_id/d',1);
        $order_goods = M('order_goods')->where("order_id", $order_id)->select();
        $delivery = M('delivery_doc')->where("order_id", $order_id)->find();
        $this->assign('order_goods', $order_goods);
        $this->assign('delivery', $delivery);
        return $this->fetch();
    }

    /*
     * 取消订单
     */
    public function cancel_order()
    {
        $id = I('get.id/d');
        //检查是否有积分，余额支付
        $logic = new UsersLogic();
        $data = $logic->cancel_order($this->user_id, $id);
        return $this->ajaxReturn($data);
//        if ($data['status'] < 0)
//            $this->error($data['msg']);
//        $this->success($data['msg']);
    }

    /*
     * 用户地址列表
     */
    public function address_list()
    {
        $address_lists = get_user_address_list($this->user_id);
        $region_list = get_region_list();
        $this->assign('region_list', $region_list);
        $this->assign('lists', $address_lists);
        $empty = '<div class="none"><img src="__STATIC__/images/none2.png"><br><br><i class="account-acco1"></i>您还没有地址!</div>';
        $this->assign('empty',$empty);
        return $this->fetch();
    }

    /*
     * 添加地址
     */
    public function add_address()
    {
        if (IS_POST){
            $source = I('source');
            $post_data = I('post.');
            $logic = new UsersLogic();
            $data = $logic->add_address($this->user_id, 0, I('post.'));
            if ($data['status'] != 1)
                $this->error($data['msg']);
            elseif ($source == 'cart2') {
                header('Location:' . U('/Mobile/Cart/cart2', array('address_id' => $data['result'])));
                exit;
            }elseif($source == 'pre_sell'){
                header('Location:' . U('/Mobile/Cart/pre_sell', array('address_id' => $data['result'],'act_id'=>$post_data['act_id'],'goods_num'=>$post_data['goods_num'])));
                exit;
            }elseif($source == 'sjvip'){
                header("Location:" . U('Mobile/user/sjvip',array('id' =>$post_data['taocan_id'])));
                exit;
            }elseif($source == 'tihuo'){
                header("Location:" . U('Mobile/user/tihuo'));
                exit;
            }

            header("Location:" . U('/Mobile/User/address_list'));
            exit();
        }
        if(!empty($_SESSION['user_address'])){
            $this->assign('user_address',$_SESSION['user_address']);
        }
        $p = M('region')->where(array('parent_id' => 0, 'level' => 1))->select();
        $address = M('user_address')->where(array('user_id' => $this->user_id))->find();
        if (empty($address)) {
            $status = 1;
        } else {
            $status = 2;
        }
        $this->assign('status',$status);
        $this->assign('province', $p);
        //return $this->fetch('edit_address');
        return $this->fetch();

    }

    /*
     * 地址编辑
     */
    public function edit_address()
    {
        $id = I('id/d');
        $address = M('user_address')->where(array('address_id' => $id, 'user_id' => $this->user_id))->find();
        if (IS_POST) {
            $logic = new UsersLogic();
            $data = $logic->add_address($this->user_id, $id, I('post.'));
            if ($_POST['source'] == 'cart2') {
                header('Location:' . U('/Mobile/Cart/cart2', array('address_id' => $id)));
                exit;
            }elseif($_POST['source'] == 'sjvip'){
                header("Location:" . U('Mobile/user/sjvip',array('id' => I('taocan_id'))));
                exit;
            }elseif($_POST['source'] == 'tihuo'){
                header("Location:" . U('Mobile/user/tihuo'));
                exit;
            } else
                header("Location:" . U('/Mobile/User/address_list'));
                exit();
        }
        //获取省份
        $p = M('region')->where(array('parent_id' => 0, 'level' => 1))->select();
        $c = M('region')->where(array('parent_id' => $address['province'], 'level' => 2))->select();
        $d = M('region')->where(array('parent_id' => $address['city'], 'level' => 3))->select();
        if ($address['twon']) {
            $e = M('region')->where(array('parent_id' => $address['district'], 'level' => 4))->select();
            $this->assign('twon', $e);
        }
        $this->assign('province', $p);
        $this->assign('city', $c);
        $this->assign('district', $d);
        $this->assign('address', $address);
        return $this->fetch();
    }

    /*
     * 设置默认收货地址
     */
    public function set_default()
    {
        $id = I('get.id/d');
        $source = I('get.source');
        M('user_address')->where(array('user_id' => $this->user_id))->save(array('is_default' => 0));
        $row = M('user_address')->where(array('user_id' => $this->user_id, 'address_id' => $id))->save(array('is_default' => 1));
        if ($source == 'cart2') {
            header("Location:" . U('Mobile/Cart/cart2'));
            exit;
        }elseif($source == 'sjvip'){
            header("Location:" . U('Mobile/user/sjvip'));
            exit;
        }elseif($source == 'tihuo'){
            header("Location:" . U('Mobile/user/tihuo'));
            exit;
        } else {
            header("Location:" . U('Mobile/User/address_list'));
        }
    }

    /*
     * 地址删除
     */
    public function del_address()
    {
        $id = I('get.id/d');

        $address = M('user_address')->where("address_id", $id)->find();
        $row = M('user_address')->where(array('user_id' => $this->user_id, 'address_id' => $id))->delete();
        // 如果删除的是默认收货地址 则要把第一个地址设置为默认收货地址
        if ($address['is_default'] == 1) {
            $address2 = M('user_address')->where("user_id", $this->user_id)->find();
            $address2 && M('user_address')->where("address_id", $address2['address_id'])->save(array('is_default' => 1));
        }
        if (!$row)
            $this->error('操作失败', U('User/address_list'),2);
        else
            $this->success("操作成功", U('User/address_list'),2);
    }

    /*
     * 评论晒单
     */
    public function comment()
    {
        $user_id = $this->user_id;
        $status = I('get.status');
        $logic = new \app\common\logic\CommentLogic;
        $result = $logic->getComment($user_id, $status); //获取评论列表
        $this->assign('comment_list', $result['result']);
        if ($_GET['is_ajax']) {
            return $this->fetch('ajax_comment_list');
            exit;
        }
        return $this->fetch();
    }

    /*
     *添加评论
     */
    public function add_comment()
    {
        if (IS_POST) {
            // 晒图片
            $files = request()->file('comment_img_file');
            $save_url = 'public/upload/comment/' . date('Y', time()) . '/' . date('m-d', time());
            foreach ($files as $file) {
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $file->rule('uniqid')->validate(['size' => 1024 * 1024 * 30, 'ext' => 'jpg,png,gif,jpeg'])->move($save_url);
                if ($info) {
                    // 成功上传后 获取上传信息
                    // 输出 jpg
                    $comment_img[] = '/'.$save_url . '/' . $info->getFilename();
                } else {
                    // 上传失败获取错误信息
                    $this->error($file->getError());
                }
            }
            if (!empty($comment_img)) {
                $add['img'] = serialize($comment_img);
            }

            $user_info = session('user');
            $logic = new UsersLogic();
            $add['goods_id'] = I('goods_id/d');
            $add['email'] = $user_info['email'];
            $hide_username = I('hide_username');
            if (empty($hide_username)) {
                $add['username'] = $user_info['nickname'];
            }
            $add['is_anonymous'] = $hide_username;  //是否匿名评价:0不是\1是
            $add['order_id'] = I('order_id/d');
            $add['service_rank'] = I('service_rank');
            $add['deliver_rank'] = I('deliver_rank');
            $add['goods_rank'] = I('goods_rank');
            $add['is'] = I('goods_rank');
            //$add['content'] = htmlspecialchars(I('post.content'));
            $add['content'] = I('content');
            $add['add_time'] = time();
            $add['ip_address'] = request()->ip();
            $add['user_id'] = $this->user_id;

            //添加评论
            $row = $logic->add_comment($add);
            if ($row['status'] == 1) {
                $this->success('评论成功', U('/Mobile/User/comment', array('status'=>1)));
                exit();
            } else {
                $this->error($row['msg']);
            }
        }
        $rec_id = I('rec_id/d');
        $order_goods = M('order_goods')->where("rec_id", $rec_id)->find();
        $this->assign('order_goods', $order_goods);
        return $this->fetch();
    }

    /*
     * 个人信息
     */
    public function userinfo()
    {
        
        $userLogic = new UsersLogic();
        $user_info = $userLogic->get_info($this->user_id); // 获取用户信息
        $user_info = $user_info['result'];

        // p($user_info);
        if (IS_POST) {
            $_POST['nickname'] ? $post['nickname'] = $_POST['nickname'] : false; //昵称
            I('post.qq') ? $post['qq'] = I('post.qq') : false;  //QQ号码
            I('post.head_pic') ? $post['head_pic'] = I('post.head_pic') : false; //头像地址
            I('post.sex') ? $post['sex'] = I('post.sex') :  false;  // 性别
            I('post.birthday') ? $post['birthday'] = strtotime(I('post.birthday')) : false;  // 生日
            I('post.province') ? $post['province'] = I('post.province') : false;  //省份
            I('post.city') ? $post['city'] = I('post.city') : false;  // 城市
            I('post.district') ? $post['district'] = I('post.district') : false;  //地区
            I('post.email') ? $post['email'] = I('post.email') : false; //邮箱
            I('post.mobile') ? $post['mobile'] = I('post.mobile') : false; //手机
            I('post.realname') ? $post['realname'] = I('post.realname') : false; //真名
            I('post.idcard') ? $post['idcard'] = I('post.idcard') : false; //身份证号

            $email = I('post.email');
            $mobile = I('post.mobile');
            $mobile2 = I('post.mobile2');
            $goods_id = I('post.goods_id');
            $code = I('post.mobile_code', '');
            $mobile_code = I('post.mobile_code');
            $scene = I('post.scene', 6);
            $idcard = I('post.idcard');
            
            if (!empty($email)) {
                $c = M('users')->where(['email' => input('post.email'), 'user_id' => ['<>', $this->user_id]])->count();
                $c && $this->error("邮箱已被使用");
            }   

            // if (!empty($idcard)) {
            //     $c = M('users')->where(['idcard' => $idcard, 'user_id' => ['<>', $this->user_id]])->count();
            //     $c && $this->error("身份证号已被");
            // }
            if (!empty($mobile2)) { 
                // $c = M('users')->where(['mobile' => input('post.mobile2'), 'user_id' => ['<>', $this->user_id]])->count();
                // $c && $this->error("手机已被使用");
                $data['mobile'] = $mobile2;
                if (!$mobile_code)
                    $this->error('请输入验证码');
                $check_code = $userLogic->check_validate_code($mobile_code, $mobile2, 'phone', $this->session_id, $scene);
                if ($check_code['status'] != 1){
                    return '2';
                }else{
                    $user = M('Users')->where(['user_id'=>$this->user_id])->save($data);
                    return '1';
                }
            }

            if (!empty($mobile)) {
                $c = M('users')->where(['mobile' => input('post.mobile'), 'user_id' => ['<>', $this->user_id]])->count();
                $c && $this->error("手机已被使用");
                if (!$code)
                    $this->error('请输入验证码');
                $check_code = $userLogic->check_validate_code($code, $mobile, 'phone', $this->session_id, $scene);
                if ($check_code['status'] != 1)
                    $this->error($check_code['msg']);
            }

            if ($_FILES['head_pic']['tmp_name']) {
                $file = $this->request->file('head_pic');
                $validate = ['size'=>1024 * 1024 * 3,'ext'=>'jpg,png,gif,jpeg'];
                $dir = 'public/upload/head_pic/';
                if (!($_exists = file_exists($dir))){
                    $isMk = mkdir($dir);
                }
                $parentDir = date('Ymd');
                $info = $file->validate($validate)->move($dir, true);
                if($info){
                    $post['head_pic'] = '/'.$dir.$parentDir.'/'.$info->getFilename();
                }else{
                    $this->error($file->getError());//上传错误提示错误信息
                }
            }



            if (!$userLogic->update_info($this->user_id, $post))
                $this->error("保存失败");
            setcookie('uname',urlencode($post['nickname']),null,'/');
            if($_SESSION['backurl']){
                // if(!alluserinfo($this->user_id)){
                //     header("location:".U('user/userinfo'));
                //     exit;
                // }else{
                //     $url=$_SESSION['backurl'];
                //     unset($_SESSION['backurl']);
                //     $this->success("操作成功",$url);                
                //     exit;
                // }                
            }
            header("location:".U('user/userinfo'));
            exit;
        }
        //  获取省份
        $province = M('region')->where(array('parent_id' => 0, 'level' => 1))->select();
        //  获取订单城市
        $city = M('region')->where(array('parent_id' => $user_info['province'], 'level' => 2))->select();
        //  获取订单地区
        $area = M('region')->where(array('parent_id' => $user_info['city'], 'level' => 3))->select();
        $this->assign('province', $province);
        $this->assign('city', $city);
        $this->assign('area', $area);
        $this->assign('user', $user_info);
        $this->assign('sex', C('SEX'));
        //从哪个修改用户信息页面进来，
        $dispaly = I('action');
        if ($dispaly != '') {
            return $this->fetch("$dispaly");
        }
        return $this->fetch();
    }

    /*
     * 邮箱验证
     */
    public function email_validate()
    {
        $userLogic = new UsersLogic();
        $user_info = $userLogic->get_info($this->user_id); // 获取用户信息
        $user_info = $user_info['result'];
        $step = I('get.step', 1);
        //验证是否未绑定过
        if ($user_info['email_validated'] == 0)
            $step = 2;
        //原邮箱验证是否通过
        if ($user_info['email_validated'] == 1 && session('email_step1') == 1)
            $step = 2;
        if ($user_info['email_validated'] == 1 && session('email_step1') != 1)
            $step = 1;
        if (IS_POST) {
            $email = I('post.email');
            $code = I('post.code');
            $info = session('email_code');
            if (!$info)
                $this->error('非法操作');
            if ($info['email'] == $email || $info['code'] == $code) {
                if ($user_info['email_validated'] == 0 || session('email_step1') == 1) {
                    session('email_code', null);
                    session('email_step1', null);
                    if (!$userLogic->update_email_mobile($email, $this->user_id))
                        $this->error('邮箱已存在');
                    $this->success('绑定成功', U('Home/User/index'));
                } else {
                    session('email_code', null);
                    session('email_step1', 1);
                    redirect(U('Home/User/email_validate', array('step' => 2)));
                }
                exit;
            }
            $this->error('验证码邮箱不匹配');
        }
        $this->assign('step', $step);
        return $this->fetch();
    }

    /*
    * 手机验证
    */
    public function mobile_validate()
    {
        $userLogic = new UsersLogic();
        $user_info = $userLogic->get_info($this->user_id); // 获取用户信息
        $user_info = $user_info['result'];
        $step = I('get.step', 1);
        //验证是否未绑定过
        if ($user_info['mobile_validated'] == 0)
            $step = 2;
        //原手机验证是否通过
        if ($user_info['mobile_validated'] == 1 && session('mobile_step1') == 1)
            $step = 2;
        if ($user_info['mobile_validated'] == 1 && session('mobile_step1') != 1)
            $step = 1;
        if (IS_POST) {
            $mobile = I('post.mobile');
            $code = I('post.code');
            $info = session('mobile_code');
            if (!$info)
                $this->error('非法操作');
            if ($info['email'] == $mobile || $info['code'] == $code) {
                if ($user_info['email_validated'] == 0 || session('email_step1') == 1) {
                    session('mobile_code', null);
                    session('mobile_step1', null);
                    if (!$userLogic->update_email_mobile($mobile, $this->user_id, 2))
                        $this->error('手机已存在');
                    $this->success('绑定成功', U('Home/User/index'));
                } else {
                    session('mobile_code', null);
                    session('email_step1', 1);
                    redirect(U('Home/User/mobile_validate', array('step' => 2)));
                }
                exit;
            }
            $this->error('验证码手机不匹配');
        }
        $this->assign('step', $step);
        return $this->fetch();
    }

    /**
     * 用户收藏列表
     */
    public function collect_list()
    {
        $userLogic = new UsersLogic();
        $data = $userLogic->get_goods_collect($this->user_id);
        $this->assign('page', $data['show']);// 赋值分页输出
        $this->assign('goods_list', $data['result']);
        if (IS_AJAX) {      //ajax加载更多
            return $this->fetch('ajax_collect_list');
            exit;
        }
        return $this->fetch();
    }

    /*
     *取消收藏
     */
    public function cancel_collect()
    {
        $collect_id = I('collect_id/d');
        $user_id = $this->user_id;
        if (M('goods_collect')->where(['collect_id' => $collect_id, 'user_id' => $user_id])->delete()) {
            $this->success("取消收藏成功", U('User/collect_list'));
        } else {
            $this->error("取消收藏失败", U('User/collect_list'));
        }
    }

    /**
     * 我的留言
     */
    public function message_list()
    {
        C('TOKEN_ON', true);
        if (IS_POST) {
            if(!$this->verifyHandle('message')){
                $this->error('验证码错误', U('User/message_list'));
            };

            $data = I('post.');
            $data['user_id'] = $this->user_id;
            $user = session('user');
            $data['user_name'] = $user['nickname'];
            $data['msg_time'] = time();
            if (M('feedback')->add($data)) {
                $this->success("留言成功", U('User/message_list'));
                exit;
            } else {
                $this->error('留言失败', U('User/message_list'));
                exit;
            }
        }
        $msg_type = array(0 => '留言', 1 => '投诉', 2 => '询问', 3 => '售后', 4 => '求购');
        $count = M('feedback')->where("user_id", $this->user_id)->count();
        $Page = new Page($count, 100);
        $Page->rollPage = 2;
        $message = M('feedback')->where("user_id", $this->user_id)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $showpage = $Page->show();
        header("Content-type:text/html;charset=utf-8");
        $this->assign('page', $showpage);
        $this->assign('message', $message);
        $this->assign('msg_type', $msg_type);
        return $this->fetch();
    }

    /**账户明细*/
    public function points()
    {
        $type = I('type', 'all');    //获取类型
        $this->assign('type', $type);
        if ($type == 'recharge') {
            //充值明细
            $count = M('recharge')->where("user_id", $this->user_id)->count();
            $Page = new Page($count, 16);
            $account_log = M('recharge')->where("user_id", $this->user_id)->order('order_id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        } else if ($type == 'points') {
            //积分记录明细
            $count = M('account_log')->where(['user_id' => $this->user_id, 'pay_points' => ['<>', 0]])->count();
            $Page = new Page($count, 16);
            $account_log = M('account_log')->where(['user_id' => $this->user_id, 'pay_points' => ['<>', 0]])->order('log_id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        } else {
            //全部
            $count = M('account_log')->where(['user_id' => $this->user_id])->count();
            $Page = new Page($count, 16);
            $account_log = M('account_log')->where(['user_id' => $this->user_id])->order('log_id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        }
        $showpage = $Page->show();
        $this->assign('account_log', $account_log);
        $this->assign('page', $showpage);
        $this->assign('listRows', $Page->listRows);
        if ($_GET['is_ajax']) {
            return $this->fetch('ajax_points');
            exit;
        }
        return $this->fetch();
    }

    
    public function points_list()
    {
    	$type = I('type','all');
    	$usersLogic = new UsersLogic;
    	$result = $usersLogic->points($this->user_id, $type);
    
    	$this->assign('type', $type);
    	$showpage = $result['page']->show();
    	$this->assign('account_log', $result['account_log']);
    	$this->assign('page', $showpage);
    	if ($_GET['is_ajax']) {
    		 return $this->fetch('ajax_points');
    	}
    	return $this->fetch();
    }
    
    
    /*
     * 密码修改
     */
    public function password()
    {
        if (IS_POST) {
            $logic = new UsersLogic();
            $data = $logic->get_info($this->user_id);
            $user = $data['result'];
            if ($user['mobile'] == '' && $user['email'] == '')
                $this->ajaxReturn(['status'=>-1,'msg'=>'请先绑定手机或邮箱','url'=>U('/Mobile/User/index')]);
            $userLogic = new UsersLogic();
            $data = $userLogic->password($this->user_id, I('post.old_password'), I('post.new_password'), I('post.confirm_password'));
            if ($data['status'] == -1)
                $this->ajaxReturn(['status'=>-1,'msg'=>$data['msg']]);
            $this->ajaxReturn(['status'=>1,'msg'=>$data['msg'],'url'=>U('/Mobile/User/index')]);
            exit;
        }
        return $this->fetch();
    }

    function forget_pwd()
    {
        if ($this->user_id > 0) {
            $this->redirect("User/index");
//            header("Location: " . U('User/Index'));`
        }
        $username = I('username');
        if (IS_POST) {
            if (!empty($username)) {
                if(!$this->verifyHandle('forget')){
                    $this->error("验证码错误");
                };
                $field = 'mobile';
                if (check_email($username)) {
                    $field = 'email';
                }
                $user = M('users')->where("email", $username)->whereOr('mobile', $username)->find();
                if ($user) {
                    session('find_password', array('user_id' => $user['user_id'], 'username' => $username,
                        'email' => $user['email'], 'mobile' => $user['mobile'], 'type' => $field));
                    header("Location: " . U('User/find_pwd'));
                    exit;
                } else {
                    $this->error("用户名不存在，请检查");
                }
            }
        }
        return $this->fetch();
    }

    function find_pwd()
    {
        if ($this->user_id > 0) {
            header("Location: " . U('User/index'));
        }
        $user = session('find_password');
        if (empty($user)) {
            $this->error("请先验证用户名", U('User/forget_pwd'));
        }
        $this->assign('user', $user);
        return $this->fetch();
    }


    public function set_pwd()
    {
        if ($this->user_id > 0) {
//            header("Location: " . U('User/Index'));
            $this->redirect('Mobile/User/index');
        }
        $check = session('validate_code');
        if (empty($check)) {
            header("Location:" . U('User/forget_pwd'));
        } elseif ($check['is_check'] == 0) {
            $this->error('验证码还未验证通过', U('User/forget_pwd'));
        }
        if (IS_POST) {
            $password = I('post.password');
            $password2 = I('post.password2');
            if ($password2 != $password) {
                $this->error('两次密码不一致', U('User/forget_pwd'));
            }
            if ($check['is_check'] == 1) {
                //$user = get_user_info($check['sender'],1);
                $user = M('users')->where("mobile", $check['sender'])->whereOr('email', $check['sender'])->find();
                M('users')->where("user_id", $user['user_id'])->save(array('password' => encrypt($password)));
                session('validate_code', null);
                //header("Location:".U('User/set_pwd',array('is_set'=>1)));
                $this->success('新密码已设置行牢记新密码', U('User/index'));
                exit;
            } else {
                $this->error('验证码还未验证通过', U('User/forget_pwd'));
            }
        }
        $is_set = I('is_set', 0);
        $this->assign('is_set', $is_set);
        return $this->fetch();
    }
 
    /**
     * 验证码验证
     * $id 验证码标示
     */
    private function verifyHandle($id)
    {
        $verify = new Verify();
        if (!$verify->check(I('post.verify_code'), $id ? $id : 'user_login')) {
            return false;
        }
        return true;
    }

    /**
     * 验证码获取
     */
    public function verify()
    {
        //验证码类型
        $type = I('get.type') ? I('get.type') : 'user_login';
        $config = array(
            'fontSize' => 30,
            'length' => 4,
            //'imageH' =>  60,
            //'imageW' =>  300,
            //'fontttf' => '5.ttf',
            'useCurve' => false,
            'useNoise' => false,
        );
        $Verify = new Verify($config);
        $Verify->entry($type);
		exit();
    }

    /**
     * 账户管理
     */
    public function accountManage()
    {
        return $this->fetch();
    }

    /**
     * 确定收货成功
     */
    public function order_confirm()
    {
        $id = I('get.id/d', 0);
        $data = confirm_order($id, $this->user_id);
        if ($data['status'] != 1) {
            $this->error($data['msg'],U('Mobile/User/order_list'));
        } else {
            $model = new UsersLogic();
            $order_goods = $model->get_order_goods($id);
            $this->assign('order_goods', $order_goods);
            return $this->fetch();
            exit;
        }
    }

    /**
     * 申请退货
     */
    public function return_goods()
    {
        $rec_id = I('rec_id',0);
        $return_goods = M('return_goods')->where(array('rec_id'=>$rec_id))->find();
        if(!empty($return_goods))
        {
            $this->error('已经提交过退货申请!',U('User/return_goods_info',array('id'=>$return_goods['id'])));
        }
        $order_goods = M('order_goods')->where(array('rec_id'=>$rec_id))->find();
        $order = M('order')->where(array('order_id'=>$order_goods['order_id'],'user_id'=>$this->user_id))->find();
        if(empty($order))$this->error('非法操作');
        if(IS_POST)
        {
            $model = new OrderLogic();
            $res = $model->addReturnGoods($rec_id,$order);  //申请售后
            if($res['status']==1)$this->success($res['msg'],U('User/return_goods_list'));
            $this->error($res['msg']);
        }
        $region_id[] = tpCache('shop_info.province');        
        $region_id[] = tpCache('shop_info.city');        
        $region_id[] = tpCache('shop_info.district');
        $region_id[] = 0;        
        $return_address = M('region')->where("id in (".implode(',', $region_id).")")->getField('id,name');
        $order_info = array_merge($order,$order_goods);  //合并数组
        $this->assign('return_address', $return_address);
        $this->assign('goods', $order_goods);
    	$this->assign('order',$order);
        return $this->fetch();
    }

    /**
     * 退换货列表
     */
    public function return_goods_list()
    {
        //退换货商品信息
        $count = M('return_goods')->where("user_id", $this->user_id)->count();
        $pagesize = C('PAGESIZE');
        $page = new Page($count, $pagesize);
        $list = M('return_goods')->where("user_id", $this->user_id)->order("id desc")->limit("{$page->firstRow},{$page->listRows}")->select();
        $goods_id_arr = get_arr_column($list, 'goods_id');  //获取商品ID
        if (!empty($goods_id_arr)){
            $goodsList = M('goods')->where("goods_id", "in", implode(',', $goods_id_arr))->getField('goods_id,goods_name');
        }
        $state = C('REFUND_STATUS');
        $this->assign('goodsList', $goodsList);
        $this->assign('list', $list);
        $this->assign('state',$state);
        $this->assign('page', $page->show());// 赋值分页输出
        if (I('is_ajax')) {
            return $this->fetch('ajax_return_goods_list');
            exit;
        }
        return $this->fetch();
    }

    /**
     *  退货详情
     */
    public function return_goods_info()
    {
        $id = I('id/d', 0);
        $return_goods = M('return_goods')->where("id = $id")->find();
        $return_goods['seller_delivery'] = unserialize($return_goods['seller_delivery']);  //订单的物流信息，服务类型为换货会显示
        if ($return_goods['imgs'])
            $return_goods['imgs'] = explode(',', $return_goods['imgs']);
        $goods = M('goods')->where("goods_id = {$return_goods['goods_id']} ")->find();
        $state = C('REFUND_STATUS');
        $this->assign('state',$state);
        $this->assign('goods', $goods);
        $this->assign('return_goods', $return_goods);
        return $this->fetch();
    }

    public function recharge()
    {
        $order_id = I('order_id/d');
        $paymentList = M('Plugin')->where("`type`='payment' and code!='cod' and status = 1 and  scene in(0,1)")->select();
        //微信浏览器
        if (strstr($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')) {
            $paymentList = M('Plugin')->where("`type`='payment' and status = 1 and code='weixin'")->select();
        }
        $paymentList = convert_arr_key($paymentList, 'code');

        foreach ($paymentList as $key => $val) {
            $val['config_value'] = unserialize($val['config_value']);
            if ($val['config_value']['is_bank'] == 2) {
                $bankCodeList[$val['code']] = unserialize($val['bank_code']);
            }
        }
        $bank_img = include APP_PATH . 'home/bank.php'; // 银行对应图片
        $payment = M('Plugin')->where("`type`='payment' and status = 1")->select();
        $this->assign('paymentList', $paymentList);
        $this->assign('bank_img', $bank_img);
        $this->assign('bankCodeList', $bankCodeList);

        if ($order_id > 0) {
            $order = M('recharge')->where("order_id", $order_id)->find();
            $this->assign('order', $order);
        }
        return $this->fetch();
    }
    
    public function recharge_list(){
    	$usersLogic = new UsersLogic;
    	$result= $usersLogic->get_recharge_log($this->user_id);  //充值记录
    	$this->assign('page', $result['show']);
    	$this->assign('lists', $result['result']);
    	if (I('is_ajax')) {
    		return $this->fetch('ajax_recharge_list');
    	}
    	return $this->fetch();
    }

     /**
     * 申请提现记录
     */
    public function withdrawals()
    {

        C('TOKEN_ON', true);
        if (IS_POST) {
            if(!$this->verifyHandle('withdrawals')){
                $this->ajaxReturn(['status'=>0,'msg'=>'验证码错误']);
            };

            $data = I('post.');
            $data['user_id'] = $this->user_id;
            $data['create_time'] = time();
            $distribut_min = tpCache('basic.min'); // 最少提现额度
            // if(encrypt($data['paypwd']) != $this->user['paypwd']){
            //     $this->error("支付密码错误");
            // }

            $users = M('Users')->where(array('user_id' => $this->user_id))->find();
            if ($data['money'] < $distribut_min) {
                $this->ajaxReturn(['status'=>0,'msg'=>'每次最少提现额度' . $distribut_min]);
                exit;
            }

            // if (!empty($idcard)) {
            //     $c = M('users')->where(['idcard' => $idcard, 'user_id' => ['<>', $this->user_id]])->count();
            //     $c && $this->error("身份证号已被占用");
            // }

            if ($data['money'] > $this->user['user_money']) {
                $this->ajaxReturn(['status'=>0,'msg'=>"你最多可提现{$this->user['user_money']}账户余额."]);
                exit;
            }
            $withdrawal = M('withdrawals')->where(array('user_id' => $this->user_id, 'status' => 0))->sum('money');
            if ($this->user['user_money'] < ($withdrawal + $data['money'])) {
                $this->ajaxReturn(['status'=>0,'msg'=>'您有提现申请待处理，本次提现余额不足']);
            }
            if ($data){
                M('withdrawals')->add($data);
                if(empty($users['idcard'])){
                    $datas['idcard'] = $data['idcard'];
                    M('Users')->where(array('user_id' => $this->user_id))->save($datas);
                }
                $this->ajaxReturn(['status'=>1,'msg'=>"已提交申请",'url'=>U('User/withdrawals_list')]);
                exit;
            } else {
                $this->ajaxReturn(['status'=>0,'msg'=>'提交失败,联系客服!']);
                exit;
            }
        }
        $this->assign('user_money', $this->user['user_money']);    //用户余额
        return $this->fetch();
    }

    /**
     * 申请记录列表
     */
    public function withdrawals_list()
    {
        $withdrawals_where['user_id'] = $this->user_id;
        $count = M('withdrawals')->where($withdrawals_where)->count();
        $pagesize = C('PAGESIZE');
        $page = new Page($count, $pagesize);
        $list = M('withdrawals')->where($withdrawals_where)->order("id desc")->limit("{$page->firstRow},{$page->listRows}")->select();

        $this->assign('page', $page->show());// 赋值分页输出
        $this->assign('list', $list); // 下线
        if (I('is_ajax')) {
            return $this->fetch('ajax_withdrawals_list');
        }
        return $this->fetch();
    }

    /**
     * 删除已取消的订单
     */
    public function order_del()
    {
        $user_id = $this->user_id;
        $order_id = I('get.order_id/d');
        $order = M('order')->where(array('order_id' => $order_id, 'user_id' => $user_id))->find();
        if (empty($order)) {
            return $this->error('订单不存在');
            exit;
        }
        $res = M('order')->where("order_id=$order_id and order_status=3")->delete();
        $result = M('order_goods')->where("order_id=$order_id")->delete();
        if ($res && $result) {
            return $this->success('成功', "mobile/User/order_list");
        } else {
            return $this->error('删除失败');
        }
    }

    /**
     * 我的关注
     * @author lxl
     * @time   2017/1
     */
    public function myfocus()
    {
        return $this->fetch();
    }

    /**
     * 待收货列表
     * @author lxl
     * @time   2017/1
     */
    public function wait_receive()
    {
        $where = ' user_id=' . $this->user_id;
        //条件搜索
        if (I('type') == 'WAITRECEIVE') {
            $where .= C(strtoupper(I('type')));
        }
        $count = M('order')->where($where)->count();
        $pagesize = C('PAGESIZE');
        $Page = new Page($count, $pagesize);
        $show = $Page->show();
        $order_str = "order_id DESC";
        $order_list = M('order')->order($order_str)->where($where)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        //获取订单商品
        $model = new UsersLogic();
        foreach ($order_list as $k => $v) {
            $order_list[$k] = set_btn_order_status($v);  // 添加属性  包括按钮显示属性 和 订单状态显示属性
            //$order_list[$k]['total_fee'] = $v['goods_amount'] + $v['shipping_fee'] - $v['integral_money'] -$v['bonus'] - $v['discount']; //订单总额
            $data = $model->get_order_goods($v['order_id']);
            $order_list[$k]['goods_list'] = $data['result'];
        }

        //统计订单商品数量
        foreach ($order_list as $key => $value) {
            $count_goods_num = '';
            foreach ($value['goods_list'] as $kk => $vv) {
                $count_goods_num += $vv['goods_num'];
            }
            $order_list[$key]['count_goods_num'] = $count_goods_num;
            //订单物流单号
            $invoice_no = M('DeliveryDoc')->where("order_id", $value['order_id'])->getField('invoice_no', true);
            $order_list[$key][invoice_no] = implode(' , ', $invoice_no);
        }
        $this->assign('page', $show);
        $this->assign('order_list', $order_list);
        if ($_GET['is_ajax']) {
            return $this->fetch('ajax_wait_receive');
            exit;
        }
        return $this->fetch();
    }

    /**
     *  用户消息通知
     * @author dyr
     * @time 2016/09/01
     */
    public function message_notice()
    {
        return $this->fetch();
    }

    /**
     * ajax用户消息通知请求
     * @author dyr
     * @time 2016/09/01
     */
    public function ajax_message_notice()
    {
        $type = I('type', 0);
        $user_logic = new UsersLogic();
        $message_model = new MessageLogic();
        if ($type == 1) {
            //系统消息
            $user_sys_message = $message_model->getUserMessageNotice();
            $user_logic->setSysMessageForRead();
        } else if ($type == 2) {
            //活动消息：后续开发
            $user_sys_message = array();
        } else {
            //全部消息：后续完善
            $user_sys_message = $message_model->getUserMessageNotice();
        }
        $this->assign('messages', $user_sys_message);
        return $this->fetch('ajax_message_notice');

    }

    //消息详情页
    public function message_detail(){
        $message_id = I('id');
        if($message_id){
            $message_info=M('message')->where(array('message_id'=>$message_id))->find();
            $this->assign('message_info',$message_info);
        }
        return $this->fetch();
    }



    /**
     * 设置消息通知
     */
    public function set_notice(){
        //暂无数据
        return $this->fetch();
    }

    /**
     * 取消售后服务
     * @author lxl
     * @time 2017-4-19
     */
    public function return_goods_cancel(){
        $id = I('id',0);
        if(empty($id))$this->error('参数错误');
        $return_goods = M('return_goods')->where(array('id'=>$id,'user_id'=>$this->user_id))->find();
        if(empty($return_goods)) $this->error('参数错误');
        M('return_goods')->where(array('id'=>$id))->save(array('status'=>-2,'canceltime'=>time()));
        $this->success('取消成功',U('User/return_goods_list'));
        exit;
    }

    /**
     * 换货商品确认收货
     * @author lxl
     * @time  17-4-25
     * */
    public function receiveConfirm(){
        $return_id=I('return_id/d');
        $return_info=M('return_goods')->field('order_id,order_sn,goods_id,spec_key')->where('id',$return_id)->find(); //查找退换货商品信息
        $update = M('return_goods')->where('id',$return_id)->save(['status'=>3]);  //要更新状态为已完成
        if($update) {
            M('order_goods')->where(array(
                'order_id' => $return_info['order_id'],
                'goods_id' => $return_info['goods_id'],
                'spec_key' => $return_info['spec_key']))->save(['is_send' => 2]);  //订单商品改为已换货
            $this->success("操作成功", U("User/return_goods_info", array('id' => $return_id)));
        }
        $this->error("操作失败");
    }

    /**
     * 浏览记录
     */
    public function visit_log()
    {
        $count = M('goods_visit')->where('user_id', $this->user_id)->count();
        $Page = new Page($count, 20);
        $visit = M('goods_visit')->alias('v')
            ->field('v.visit_id, v.goods_id, v.visittime, g.goods_name, g.shop_price, g.cat_id')
            ->join('__GOODS__ g', 'v.goods_id=g.goods_id')
            ->where('v.user_id', $this->user_id)
            ->order('v.visittime desc')
            ->limit($Page->firstRow, $Page->listRows)
            ->select();

        /* 浏览记录按日期分组 */
        $curyear = date('Y');
        $visit_list = [];
        foreach ($visit as $v) {
            if ($curyear == date('Y', $v['visittime'])) {
                $date = date('m月d日', $v['visittime']);
            } else {
                $date = date('Y年m月d日', $v['visittime']);
            }
            $visit_list[$date][] = $v;
        }

        $this->assign('visit_list', $visit_list);
        if (I('get.is_ajax', 0)) {
            return $this->fetch('ajax_visit_log');
        }
        return $this->fetch();
    }

    /**
     * 删除浏览记录
     */
    public function del_visit_log()
    {
        $visit_ids = I('get.visit_ids', 0);
        $row = M('goods_visit')->where('visit_id','IN', $visit_ids)->delete();

        if(!$row) {
            $this->error('操作失败',U('User/visit_log'));
        } else {
            $this->success("操作成功",U('User/visit_log'));
        }
    }

    /**
     * 清空浏览记录
     */
    public function clear_visit_log()
    {
        $row = M('goods_visit')->where('user_id', $this->user_id)->delete();

        if(!$row) {
            $this->error('操作失败',U('User/visit_log'));
        } else {
            $this->success("操作成功",U('User/visit_log'));
        }
    }

    /**
     * 支付密码
     * @return mixed
     */
    public function paypwd()
    {
        //检查是否第三方登录用户
        $user = M('users')->where('user_id', $this->user_id)->find();;
        if ($user['mobile'] == '')
            $this->error('请先绑定手机号',U('User/userinfo',['action'=>'mobile']));
        $step = I('step', 1);
        if ($step > 1) {
            $check = session('validate_code');
            if (empty($check)) {
                $this->error('验证码还未验证通过', U('mobile/User/paypwd'));
            }
        }
        if (IS_POST && $step == 2) {
            $new_password = trim(I('new_password'));
            $confirm_password = trim(I('confirm_password'));
            $oldpaypwd = trim(I('old_password'));
            //以前设置过就得验证原来密码
            if(!empty($user['paypwd']) && ($user['paypwd'] != encrypt($oldpaypwd))){
                $this->ajaxReturn(['status'=>-1,'msg'=>'原密码验证错误！','result'=>'']);
            }
            $userLogic = new UsersLogic();
            $data = $userLogic->paypwd($this->user_id, $new_password, $confirm_password);
            $this->ajaxReturn($data);
            exit;
        }
        $this->assign('step', $step);
        return $this->fetch();
    }
    /**
     *  点赞
     * @author lxl
     * @time  17-4-20
     * 拷多商家Order控制器
     */
    public function ajaxZan()
    {
        $comment_id = I('post.comment_id/d');
        $user_id = $this->user_id;
        $comment_info = M('comment')->where(array('comment_id' => $comment_id))->find();  //获取点赞用户ID
        $comment_user_id_array = explode(',', $comment_info['zan_userid']);
        if (in_array($user_id, $comment_user_id_array)) {  //判断用户有没点赞过
            $result['success'] = 0;
        } else {
            array_push($comment_user_id_array, $user_id);  //加入用户ID
            $comment_user_id_string = implode(',', $comment_user_id_array);
            $comment_data['zan_num'] = $comment_info['zan_num'] + 1;  //点赞数量加1
            $comment_data['zan_userid'] = $comment_user_id_string;
            M('comment')->where(array('comment_id' => $comment_id))->save($comment_data);
            $result['success'] = 1;
        }
        exit(json_encode($result));
    }

    public function vip(){
        return $this->fetch();
    }
    
    //升级VIP订单页面
    public function sjvip(){
        if($this->user_id == 0){
            $this->error('请先登录',U('mobile/User/login'));
        }        
        // if(!alluserinfo($this->user_id)){
        //     $_SESSION['backurl']='http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
        //     $this->error('请先完善个人信息',U('mobile/User/userinfo'));
        // }
        $id=I('get.id');
        $address_id=I('get.address_id');
        $taocan = M('taocan')->where(array('id'=>$id))->find();
        if($address_id){
            $address = M('user_address')->where("address_id", $address_id)->find();
        } else {
            $address = M('user_address')->where(['user_id'=>$this->user_id,'is_default'=>1])->find();
        }
        if(empty($address)){
            header("Location: ".U('Mobile/User/add_address',array('source'=>'sjvip','taocan_id'=>$id)));
            exit;
        }else{
            $this->assign('address',$address);
        }
        
        $userinfo=M('users')->where(array('user_id'=>$this->user_id))->find();
        if($taocan){            
            if(!in_array($userinfo['level'],unserialize($taocan['show_level']))){
                $this->error('你不能购买该套餐',U('mobile/User/index'));
            }
        }
        $cartList = M('goods')->where(array('goods_id'=>$taocan['goods_id']))->find();
        $cartList['goods_num']=$taocan['goods_num'];
        $cartPriceInfo=$cartList['shop_price']*$cartList['goods_num']*$taocan['taocan_price']/100;
        //$shippingList = M('Plugin')->where("`type` = 'shipping' and status = 1")->cache(true,TPSHOP_CACHE_TIME)->select();// 物流公司
        //$this->assign('shippingList', $shippingList); // 物流公司
        $this->assign('cartList', $cartList); // 购物车的商品
        $this->assign('cartPriceInfo',$cartPriceInfo);
        $this->assign('taocan',$taocan);
        $this->assign('user',$userinfo);
        return $this->fetch();
    }
    //推广二维码
    public function extended(){
        $user_id=I('id',0);
        // if(!$this->user_id){
        //     $_SESSION['fuid']=$user_id;
        //     header("Location:".U('Mobile/User/wx_login'));
        //     exit;
        // }        
        $user = M('Users')->where(['user_id'=>$user_id])->find();
        $name='public/images/erweima_'.$user['user_id'].'.jpeg';
        if(@fopen("http://".$_SERVER['HTTP_HOST']."/".$name,'r')){
            $this->assign('img', "http://".$_SERVER['HTTP_HOST']."/".$name);
        }else{
            $img=$this->gzh_ewm($user_id);
            $background='public/images/extension5.png';
            $text='hello';
            $this->mark_photo($background,$img,$text,$name);
            $this->assign('img', "http://".$_SERVER['HTTP_HOST']."/".$name);
        }
        
        $this->assign('url', $url);        
        $this->assign('user', $user);
        return $this->fetch();
    }
    public function mark_photo($background,$code,$text,$name){
                
        $back=imagecreatefrompng($background);            
        $color=imagecolorallocate($back,14,87,51);           
        $code=imagecreatefromjpeg($code);           
        $code_w=imagesx($code);
        $code_h=imagesy($code);  
        $font="public/font/MSYH.ttf";           
        //imagettftext只认utf8字体，所以用iconv转换
        //imagettftext($back,14,0,200,395,$color,$font,"邀请您参加丰席树推广活动");        
        //imagettftext($back,18,0,230,365,$color,$font,"打开微信扫一扫");        
        //合成二维码
        imagecopyresampled($back, $code, 220,385, 0, 0, 300, 300, $code_w, $code_h);
        imagejpeg($back,$name);           
        imagedestroy($back);
        imagedestroy($code);
    }

    /**
     * 升级VIP订单价格统计
     */
    public function carttongji(){
        if($this->user_id == 0){
            exit(json_encode(array('status'=>-100,'msg'=>"登录超时请重新登录!",'result'=>null))); // 返回结果状态
        }
        $id = I("taocanid");
        $taocan = M('taocan')->where(array('id'=>$id))->find();

        $address_id = I("address_id/d"); //  收货地址id
        $shipping_code =  I("shipping_code",'shentong'); //  物流编号        
        $invoice_title = I('invoice_title'); // 发票
        $coupon_id =  I("coupon_id/d"); //  优惠券id
        $couponCode =  I("couponCode"); //  优惠券代码
        $pay_points =  I("pay_points/d",0); //  使用积分
        $user_money =  I("user_money/f",0); //  使用余额        
        $user_note =  I("user_note",''); // 用户留言
        $paypwd =  I("paypwd",''); // 支付密码
        $user_money = $user_money ? $user_money : 0;

        
        if(!$address_id) exit(json_encode(array('status'=>-3,'msg'=>'请先填写收货人信息','result'=>null))); // 返回结果状态
        if(!$shipping_code) exit(json_encode(array('status'=>-4,'msg'=>'请选择物流信息','result'=>null))); // 返回结果状态
        
        $address = M('UserAddress')->where("address_id", $address_id)->find();
        $goodinfo=M('goods')->where(array('goods_id'=>$taocan['goods_id']))->find();
        $order_goods[0] = array('goods_id'=>$goodinfo['goods_id'],'goods_sn'=>$goodinfo['goods_sn'],'goods_name'=>$goodinfo['goods_name'],'market_price'=>$goodinfo['market_price'],'goods_price'=>$goodinfo['shop_price'],'member_goods_price'=>$goodinfo['shop_price']*$taocan['taocan_price']/100,'goods_num'=>$taocan['goods_num']);
        $result = calculate_price($this->user_id,$order_goods,$shipping_code,0,$address['province'],$address['city'],$address['district'],$pay_points,$user_money,$coupon_id,$couponCode);
        if($result['status'] < 0) exit(json_encode($result));       
        
        $car_price = array(
            //'postFee'      => $result['result']['shipping_price'], // 物流费
            'postFee'      => 0, // 物流费
            'couponFee'    => $result['result']['coupon_price'], // 优惠券            
            'balance'      => $result['result']['user_money'], // 使用用户余额
            'pointsFee'    => $result['result']['integral_money'], // 积分支付            
            'payables'     => number_format($result['result']['order_amount'], 2, '.', ''), // 应付金额
            'goodsFee'     => $result['result']['goods_price'],// 商品价格            
            'order_prom_id' => 0, // 订单优惠活动id
            'order_prom_amount' => $goodinfo['shop_price']*$taocan['goods_num']*(100-$taocan['taocan_price'])/100, // 订单优惠活动优惠了多少钱
        );

        // 提交订单
        if ($_REQUEST['act'] == 'submit_order') {
            $pay_name = '';
            $sendkc =  I("sendkc"); // 发货or库存
            if ($pay_points || $user_money) {
                if ($this->user['is_lock'] == 1) {
                    exit(json_encode(array('status'=>-5,'msg'=>"账号异常已被锁定，不能使用余额支付！",'result'=>null))); // 用户被冻结不能使用余额支付
                }                
                $pay_name = $user_money ? '余额支付' : '积分兑换';
            }
            
            if(empty($coupon_id) && !empty($couponCode))
               $coupon_id = M('CouponList')->where("code", $couponCode)->getField('id');
            $orderLogic = new OrderLogic();
            $result = $orderLogic->addOrder($this->user_id,$address_id,$shipping_code,$invoice_title,$coupon_id,$car_price,$user_note,$pay_name,1,$id,$sendkc); // 添加订单
            exit(json_encode($result));            
        }
        
        $return_arr = array('status'=>1,'msg'=>'计算成功','result'=>$car_price); // 返回结果状态
        exit(json_encode($return_arr));           
    }



    public function wx_login(){
        //微信浏览器
        if(strstr($_SERVER['HTTP_USER_AGENT'],'MicroMessenger')){
            $user_temp = session('user');
            if (isset($user_temp['user_id']) && $user_temp['user_id']) {
                $user = M('users')->where("user_id", $user_temp['user_id'])->find();
                if (!$user) {
                    $_SESSION['openid'] = 0;
                    session('user', null);
                }
            }
            if (empty($_SESSION['openid'])) {
                $this->weixin_config = M('wx_user')->find(); //获取微信配置
                $this->assign('wechat_config', $this->weixin_config); 
                if(is_array($this->weixin_config) && $this->weixin_config['wait_access'] == 1){
                    $wxuser = $this->GetOpenid(); //授权获取openid以及微信用户信息
                    
                    $subscribe = $this->is_subscribe($wxuser);

                    session('subscribe', $subscribe['subscribe']);// 当前这个用户是否关注了微信公众号
                    if($subscribe['subscribe']==0){
                        unset($_SESSION['openid']);
                        $this->success('您还没有关注公众号，请关注公众号！', U('mobile/user/gongzhonghao'));
                        exit;
                    }

                    //微信自动登录                             
                    $logic = new UsersLogic();
                    $data = $logic->thirdLogin($wxuser);                                
                    if($data['status'] == 1){
                        session('user',$data['result']);
                        setcookie('user_id',$data['result']['user_id'],null,'/');
                        setcookie('is_distribut',$data['result']['is_distribut'],null,'/');
                        setcookie('uname',$data['result']['nickname'],null,'/');                    
                        // 登录后将购物车的商品的 user_id 改为当前登录的id
                        M('cart')->where("session_id", $this->session_id)->save(array('user_id'=>$data['result']['user_id']));
                        $cartLogic = new CartLogic();
                        $cartLogic->setUserId($data['result']['user_id']);
                        $cartLogic->doUserLoginHandle();// 用户登录后 需要对购物车 一些操作   
                    }
                }
            }

            $this->public_assign();
            
            // $subscribe = $this->is_subscribe($wxuser);
            // session('subscribe', $subscribe['subscribe']);// 当前这个用户是否关注了微信公众号
            // if($subscribe['subscribe']==0){
            //     unset($_SESSION['openid']);
            //     $this->success('您还没有关注公众号，请关注公众号！', U('mobile/user/gongzhonghao'));
            //     exit;
            // }
        }
        
        header("Location: http://".$_SERVER['HTTP_HOST']."/mobile/user/index");
        exit;
    }

    public function distribution(){
        return $this->fetch();
    }

    public function gongzhonghao(){
        return $this->fetch();
    }

    public function lower_list(){
        $level = I('get.level',1);
        $q = I('post.q','','trim');
        $condition = array(1=>'first_leader',2=>'second_leader',3=>'third_leader');
        $where = "{$condition[$level]} = {$this->user_id}";
        $q && $where .= " and (nickname like '%$q%' or user_id = '$q' or mobile = '$q')";
    
        $count = M('users')->where($where)->count();
        $page = new Page($count,10);
        $list = M('users')->where($where)->limit("{$page->firstRow},{$page->listRows}")->order('user_id desc')->select();
        foreach($list as $k=>$v){
             $reb_sum = M('rebate_log')->query("select sum(money) as money from tp_rebate_log where user_id =".$this->user_id." and buy_user_id =".$v['user_id']);
             $list[$k]['buyer_money'] = $reb_sum[0]['money']>0?$reb_sum[0]['money']:0;
        }
//        print_r($list);die;
        $this->assign('count', $count);// 总人数
        $this->assign('level',$level);
        $this->assign('page', $page->show());// 赋值分页输出
        $this->assign('member',$list); // 下线
        return $this->fetch();
    }

    public function income(){        
        $condition['user_id'] = $this->user_id;
        if(I('get.user_id')){
            $condition['buy_user_id'] = I('get.user_id');
            $money = M('rebate_log')->query("select sum(money) as money from tp_rebate_log where user_id =".$condition['user_id']." and buy_user_id =".$condition['buy_user_id']);
        }else{
            $money = M('rebate_log')->query("select sum(money) as money from tp_rebate_log where user_id =".$condition['user_id']);
        }

        $count = M('rebate_log')->where($condition)->count();
        $levelinfo=M('user_level')->select();
        foreach ($levelinfo as $key => $value) {
            $level[$value['level_id']]=$value;
        }
        $page = new Page($count,10);
        $rebate_log = M('rebate_log')->where($condition)->limit("{$page->firstRow},{$page->listRows}")->order('id desc')->select();
        $this->assign('page', $page->show());// 赋值分页输出
        $this->assign('money', $money[0]['money']);// 赋值分页输出
        $this->assign('rebate_log',$rebate_log);
        $this->assign('level',$level);
        return $this->fetch();
    }

    public function tihuo(){
        //库存商品信息
        $user_id = $this->user_id;
        $user_kucun=M('users_kucun')->where(array('user_id'=>$user_id))->find();
        $goodslists=M('goods')->select();
        foreach ($goodslists as $key => $value) {
            $goodslist[$value['goods_id']]=$value;
        }
        if($user_kucun){
            $user_kucun=unserialize($user_kucun['kucun']);
        }else{
            $user_kucun=null;
        } 
        $this->assign('goodslist', $goodslist);
        $this->assign('user_kucun', $user_kucun);

        if(IS_POST){
            $address_id = I("address_id/d"); //  收货地址id
            $checkItem = $_POST['checkItem']; //  商品信息
            $shipping_code =  I("shipping_code",'ems'); //  物流编号
            $user_note = trim(I('user_note'));   //买家留言
            //判断信息是否正确 是否超库存
            if(!$address_id){
                $this->error('收货地址不能为空',U("Mobile/User/tihuo"));
                exit;
            }
            if(!$shipping_code){
                $this->error('物流方式不能为空',U("Mobile/User/tihuo"));
                exit;
            }
            //取出用户提交的商品id和数量
            foreach ($checkItem as $key => $value) {
                $data=explode('_',$value);
                $kucun[$data[0]]=$data[1];
            }
            foreach ($kucun as $key => $value) {
                if($value>$user_kucun[$key]){
                    $this->error('您有商品提货数额超出您的库存',U("Mobile/User/tihuo"));
                    exit;
                }
                $user_kucun[$key]=$user_kucun[$key]-$value;
                //if($user_kucun[$key]-$value){unset($user_kucun[$key]);}
            }
            //生成提货订单
            $address = M('UserAddress')->where(array('address_id' => $address_id))->find();
            if($shipping_code!='ziti'){
                //$shipping = M('Plugin')->where(array('code' => $shipping_code))->find();
                $shipping['name']='邮政物流';
                $is_ziti=0;
            }else{
                $is_ziti=1;
                $shipping['name']="自提";
            }

            $tihuo_sn = null;
            // 保证不会有重复订单号存在
            while(true){
                $tihuo_sn = date('YmdHis').rand(1000,9999); // 订单编号         
                $tihuo_sn_count = M('users_tihuo')->where("tihuo_sn = ".$tihuo_sn)->count();
                if($tihuo_sn_count == 0)
                    break;
            }
            
            $data = array(
                'user_id'          =>$user_id, // 用户id
                'kucun'            =>serialize($kucun),//提货商品id+数量
                'order_status'     =>1, // 订单状态
                'shipping_status'  =>0, // 发货状态
                'consignee'        =>$address['consignee'], // 收货人
                'province'         =>$address['province'],//'省份id',
                'city'             =>$address['city'],//'城市id',
                'district'         =>$address['district'],//'县',
                'twon'             =>$address['twon'],// '街道',
                'address'          =>$address['address'],//'详细地址',
                'mobile'           =>$address['mobile'],//'手机',
                'shipping_code'    =>$shipping_code,//'物流编号',
                'shipping_name'    =>$shipping['name'], //'物流名称',                
                'add_time'         =>time(), // 下单时间
                'user_note'        =>$user_note, //用户下单备注
                'is_ziti'          =>$is_ziti,//是否自提
                'tihuo_sn'         =>$tihuo_sn//提货单号
            );
            $tihuo_id=M("users_tihuo")->insertGetId($data);
            //修改库存
            M('users_kucun')->where(array('user_id'=>$user_id))->save(array('kucun'=>serialize($user_kucun)));
            //增加提货记录
            $datas=array(
                'user_id'          =>$user_id, // 用户id
                'kucun'            =>serialize($kucun),//提货商品id+数量
                'create_time'      =>time(), // 下单时间
                'status'           =>2,//取货
                'tihuo_id'         =>$tihuo_id,
                'tihuo_sn'         =>$tihuo_sn
                );
            M("users_kucun_log")->insert($datas);            
            //跳转我的库存页面
            $this->success('提取库存成功', U('mobile/user/kucun'));
            exit;
        }        

        //地址信息
        $address_id = I('address_id/d');
        if($address_id){
            $address = M('user_address')->where("address_id", $address_id)->find();
        } else {
            $address = M('user_address')->where(['user_id'=>$this->user_id,'is_default'=>1])->find();
        }
        $this->assign('address',$address);

        //物流信息
        //$shippingList = M('Plugin')->where("`type` = 'shipping' and status = 1")->cache(true,TPSHOP_CACHE_TIME)->select();// 物流公司
        //$this->assign('shippingList', $shippingList); // 物流公司

        return $this->fetch();
    }

    /*
    *微信位置
    */
    public function weixin_address(){
        $lat = I('get.latitude');
        $lng = I('get.longitude');
        $c=file_get_contents("http://api.map.baidu.com/ag/coord/convert?from=0&to=4&x=$lng&y=$lat");
        $arr=(array)json_decode($c);
        if(!$arr['error'])
        {
            $lat=base64_decode($arr['y']);
            $lng=base64_decode($arr['x']);
        }
        //return array($lat,$lng);
        $url='http://api.map.baidu.com/geocoder/v2/?output=json&ak=VdCyE3p1mdY9f2YPSFIihzOzPdt7qyuL&location='.$lat.','.$lng;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
         
        $res = curl_exec($curl);
        curl_close($curl);
        $res = json_decode($res,true);     
        $provinceid = M('region')->where(array('parent_id'=>'0','name' => $res['result']['addressComponent']['province']))->field('id,name')->find();                
        $city =  M('region')->where(array('parent_id'=>"$provinceid[id]",'name' => $res['result']['addressComponent']['city']))->field('id,name')->find();      
        $district =  M('region')->where(array('parent_id'=>"$city[id]",'name' => $res['result']['addressComponent']['district']))->field('id,name')->find();
        $wx_address=array('province'=>$provinceid['id'],'city'=>$city['id'],'district'=>$district['id'],'province_name'=>$provinceid['name'],'city_name'=>$city['name'],'district_name'=>$district['name']);
        session('user_address',$wx_address);
        $data['status']=1;
        echo json_encode($data);//数组 改
        exit;      
    }

    /*
     * 提货单详情
     */
    public function tihuo_detail(){
        $id = I('get.id/d');
        $map['id'] = $id;
        $map['user_id'] = $this->user_id;
        $order_info = M('users_tihuo')->where($map)->find();
        if(!$order_info){
            $this->error('没有获取到提货单信息');
            exit;
        }
        $goodslists=M('goods')->select();
        foreach ($goodslists as $key => $value) {
            $goodslist[$value['goods_id']]=$value;
        }
        $user_kucun=unserialize($order_info['kucun']);

        $region_list = get_region_list();

        $this->assign('region_list',$region_list);
        $this->assign('goodslist',$goodslist);
        $this->assign('user_kucun',$user_kucun);
        $this->assign('order_info',$order_info);
        return $this->fetch();
    }

    //确认收货
    public function tihuo_confirm()
    {
        $tihuo_id = I('post.tihuo_id/d', 0);
        $result=M('users_tihuo')->where(array('user_id'=> $this->user_id,'id'=>$tihuo_id))->save(array('order_status'=>4,'confirm_time'=>time()));
        if($result){
            $data=array('status'=>1,'msg'=>'操作成功','url'=>U('user/tihuo_detail',['id'=>$tihuo_id]));
        }else{
            $data=array('status'=>-3,'msg'=>'操作失败');
        }
        $this->ajaxReturn($data);
    }

    public function ceshi(){
        $user_id=I('id',0);        
        $this->gzh_ewm($user_id);
    }

    public function getAddressCode(){
        $provinceName = I('post.provinceName');
        $cityName = I('post.cityName');
        $countryName = I('post.countryName');

        $provinceid = M('region')->where(array('parent_id'=>'0','name' => $provinceName))->field('id')->find();                
        $city =  M('region')->where(array('parent_id'=>"$provinceid[id]",'name' => $cityName))->field('id')->find();      
        $district =  M('region')->where(array('parent_id'=>"$city[id]",'name' => $countryName))->field('id')->find();

        $data = ['provinceid'=>$provinceid['id'],'cityid'=>$city['id'],'districtid'=>$district['id']];

        $this->ajaxReturn(['status'=>1,'msg'=>$data]);
    }


}
